package com.shushan.network.listener;

import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.android.net.bean.NetBaseBean;
import com.android.net.bean.NetRetBean;
import com.android.net.listener.async.NetHandleListener;
import com.android.net.listener.common.CallbackCode;
import com.android.net.util.NetBaseBeanUtil;
import com.shushan.base.Constants;
import com.shushan.shushanbao.BabyApplication;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @ClassName: NetSingleCommListener
 * @Desciption: 返回是单个Bean的网络请求Listener
 * @author: yichaohua
 * @date: 2018-05-07
 */
abstract public class NetSingleCommListener<T extends NetBaseBean> extends NetHandleListener {

    private static final String TAG = "NetSingleCommListener";

    @Override
    protected void onReceivedRet(NetRetBean netRetBean) throws JSONException {

        int reset = netRetBean.getReset();
        Log.i(TAG,"onReceivedRet reset=" + reset);
        if(reset == 1){
            Intent intent = new Intent();
            intent.setAction(Constants.USER_CHANGE_RECEIVER_ACTION);
            LocalBroadcastManager.getInstance(BabyApplication.getInstance()).sendBroadcast(intent);
        }

        JSONObject object = new JSONObject(netRetBean.getServerData());
        T t = NetBaseBeanUtil.parseItem(getClass(), 0, object);
        netRetBean.setServerObject(t);
        handleResult(netRetBean);
    }

    @Override
    protected void onSuccess(CallbackCode successCode, NetRetBean netRetBean) {
        onSuccess((T) netRetBean.getServerObject());
    }

    /**
     * 运行在ui线程，返回单个实体
     *
     * @param t 当前bean
     */
    abstract protected void onSuccess(T t);
}
